/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameheart.server;

import gameheart.transport.MyException;
import gameheart.transport.Transporter;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author win7
 */
public class ServerAdapterManager {

    private int _maxAdapterNumber;
    private int _currentAdapterNumber;

    public ServerAdapterManager(int maxAdapter) {
        _maxAdapterNumber = maxAdapter;
        _adapters = new AtomicReferenceArray<ServerAdapter>(maxAdapter);
        _currentAdapterNumber = 0;
    }
    private AtomicReferenceArray<ServerAdapter> _adapters;
    private int drawedNumber = 0;

    /***
     * reset lai do nguoi so client da ve nuoc di xong
     */
    public void reSetDrawedNumber() {
        drawedNumber = 0;
    }

    /**
     * thong bao rang client da ve nuoc di xong
     * @param adapter adapter da ve xong
     */
    public void DrawedNotify(ServerAdapter adapter) {
        drawedNumber++;
    }

    /**
     * kiem tra xen tat cac cac client da ve nuoc di xong het chua
     * @return true : tat cac da ve xong, false: nguoc lai
     */
    public boolean DrawedAll() {
        if (drawedNumber >= _adapters.length()) {
            return true;
        }
        return false;
    }

    public ServerAdapter CreateServerAdapter(Transporter transporter, ServerController controller) {
        ServerAdapter adapter = null;
        if (getCurrentAdapterNumber() < getMaxAdapterNumber()) {
            adapter = new ServerAdapter(transporter, controller);
            adapter.setUserID(getCurrentAdapterNumber());
            try {
                adapter.SendUserIdOfPlayer(getCurrentAdapterNumber());
            } catch (MyException ex) {
                Logger.getLogger(ServerAdapterManager.class.getName()).log(Level.SEVERE, null, ex);
            }
            _adapters.set(getCurrentAdapterNumber(), adapter);
            ++_currentAdapterNumber;
            Thread thread = new Thread(adapter);
            thread.start();
        }
        return adapter;
    }
    public ServerAdapter getAdapter(int id)
    {
        return _adapters.get(id);
    }

    /**
     * @return the _maxAdapterNumber
     */
    public int getMaxAdapterNumber() {
        return _maxAdapterNumber;
    }

    /**
     * @return the _currentAdapterNumber
     */
    public int getCurrentAdapterNumber() {
        return _currentAdapterNumber;
    }
}
